import React from 'react';
import Notification from 'rc-notification';
import { Icon, Toast } from 'antd-mobile';

const XLoading = () => {
  let notification;
  let seq = 0;
  const items = [];
  const prefixCls = 'am-toast';
  const content = '加载中 ...';

  const init = () => {
    Notification.newInstance({
      prefixCls,
      style: { }, // clear rc-notification default style
      transitionName: 'am-fade',
      className: `${prefixCls}-mask`,
    }, n => (notification = n));
  };

  const notice = () => {
    if (!notification) init();

    notification.notice({
      duration: 0,
      style: {},
      content: (
        <div className={`${prefixCls}-text ${prefixCls}-text-icon`} role="alert" aria-live="assertive">
          <Icon type="loading" size="lg" />
          <div className={`${prefixCls}-text-info`}>{content}</div>
        </div>
      ),
      closable: true,
      onClose: () => {
        notification.destroy();
        notification = null;
      },
    });
  };

  const show = () => {
    seq += 1;

    if (!items.length) {
      notice();
    }

    items.push(seq);
    return seq;
  };

  const hide = (id) => {
    const pos = items.indexOf(id);
    if (pos > -1) {
      items.splice(pos, 1);
    }

    if (!items.length && notification) {
      notification.destroy();
      notification = null;
    }
  };

  return { show, hide };
};

export default XLoading();
